/**
 * Created by Jing on 2018-02-26.
 */
import {
  call, put, all, takeEvery, takeLatest, select,
} from 'redux-saga/effects'
import { delay } from 'redux-saga'
import { push } from 'connected-react-router'
import { global as globalDuck } from 'ducks'
import getUserById from 'graphql/user/getUserById.graphql'
import { gqlQuery, gqlMutation } from './utils'

function* initGlobal() {
  const userId = yield select(globalDuck.selectors.userId)
  if (userId) {
    const result = yield call(gqlQuery, getUserById, { id: userId })
    if (result.user) {
      if (result.user.length === 1) {
        yield put(globalDuck.creators.actionReciveUser(result.user[0]))
      } else {
        yield put(push('/sign-up'))
      }
    } else {
      yield put(push('/'))
    }
  }
  yield put(globalDuck.creators.actionInitFinished())
}

function* checkReturnUrl() {
  const url = yield select(globalDuck.selectors.returnUrl)
  console.log('^^^^^^^^^^^^^^^^^&&&&&&&&&&&&&&&&&', url)
  if (url) {
    yield put(globalDuck.creators.actionResetReturnUrl())
    yield put(push(url))
  }
}

function* delayAction(action) {
  yield call(delay, action.time)
  yield put(action.action(...action.params))
}

export default function* sagas() {
  yield all([
    takeEvery(globalDuck.types.INIT, initGlobal),
    takeEvery(globalDuck.types.CHECK_RETURN_URL, checkReturnUrl),
    takeLatest(globalDuck.types.DELAY_ACTION, delayAction),
  ])
}
